package com.egao.common.publicly;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.egao.common.core.annotation.OperLog;
import com.egao.common.core.security.ValidateCodeException;
import com.egao.common.core.web.JsonResult;
import com.egao.common.module.company.constants.CompanyConstants;
import com.egao.common.module.company.entity.Company;
import com.egao.common.module.company.entity.vo.CompanyForgotFormVO;
import com.egao.common.module.company.entity.vo.CompanyFormVO;
import com.egao.common.module.company.service.CompanyService;
import com.egao.common.module.system.service.UserService;
import com.egao.common.publicly.service.PubliclyCompanyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 单位
 *
 * @author pyx
 */
@Api(tags = "单位")
@RestController
@RequestMapping("${api}")
public class PubliclyCompanyController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private PubliclyCompanyService publiclyCompanyService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private UserService userService;

    @ApiOperation("详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "query"),
    })
    @GetMapping("/publicly/company/get")
    public JsonResult get(Integer id) {
        if (id == null) {
            return JsonResult.error("参数为空");
        }

        Company company = publiclyCompanyService.getId(id);
        if (company == null) {
            return JsonResult.ok("单位信息不存在").setData(new Company());
        }

        return JsonResult.ok().setData(company);
    }

    @ApiOperation("单位注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyFormVO", value = "companyFormVO", required = true, dataType = "CompanyFormVO")
    })
    @OperLog(value = "单位注册", desc = "单位注册")
    @PostMapping("/publicly/company/register")
    public JsonResult register(@Valid @RequestBody CompanyFormVO companyFormVO) {
        if (StrUtil.isBlank(companyFormVO.getCode())) {
            return JsonResult.error("验证码为空");
        }

        if (StrUtil.isBlank(companyFormVO.getCodeKey())) {
            return JsonResult.error("验证码为空!");
        }

        String today = DatePattern.PURE_DATE_FORMAT.format(new DateTime());
        if (Boolean.FALSE.equals(redisTemplate.hasKey(today + companyFormVO.getCodeKey()))) {
            return JsonResult.error("验证码已过期");
        }

        String redisCode = redisTemplate.opsForValue().get(today + companyFormVO.getCodeKey());
        if (!companyFormVO.getCode().equalsIgnoreCase(redisCode)) {
            return JsonResult.error("验证码不正确");
        }

        return companyService.registerCompany(companyFormVO);
    }

    @ApiOperation("单位用户账号是否重复查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "username", required = true, dataType = "int", paramType = "String"),
    })
    @GetMapping("/publicly/company/get-username")
    public JsonResult queryUserName(String username) {
        if (StrUtil.isBlank(username)) {
            JsonResult.error("单位用户名为空");
        }
        return JsonResult.ok().setData(userService.getUserIsExistByUserName(username));
    }

    @ApiOperation("获取单位字典数据")
    @GetMapping("/publicly/company/get-dict")
    public JsonResult getDict() {
        return companyService.getDict();
    }

    @ApiOperation("单位社会统一信用代码是否重复查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "organizationCode", value = "organizationCode", required = true, dataType = "int", paramType = "String"),
    })
    @GetMapping("/publicly/company/get-code")
    public JsonResult queryOrganizationCode(String organizationCode) {
        if (StrUtil.isBlank(organizationCode)) {
            return JsonResult.error("单位社会统一信用代码为空");
        }

        if (organizationCode.length() != CompanyConstants.CODE_CREDIT_LENGTH) {
            return JsonResult.error("单位社会统一信用代码为18位");
        }
        // 组织机构代码
        // 20220519注释 原因：新的机构代码这个验证不了
//        if (organizationCode.length() == CompanyConstants.CODE_ORGANIZATION_LENGTH && !RegexUtil.isOrganizationCertificate(organizationCode)) {
//            return JsonResult.error("单位组织机构代码不正确");
//        }
//        if (organizationCode.length() == CompanyConstants.CODE_CREDIT_LENGTH && !CreditCodeUtil.isCreditCode(organizationCode)) {
//            return JsonResult.error("单位社会统一信用代码不正确");
//        }
        return JsonResult.ok().setData(companyService.getUserIsExistByOrganizationCode(organizationCode));
    }

    @ApiOperation("忘记密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyForgotFormVO", value = "companyForgotFormVO", required = true, dataType = "CompanyForgotFormVO")
    })
    @PostMapping("/publicly/company/forgot")
    public JsonResult forgotPassword(@Valid @RequestBody CompanyForgotFormVO companyForgotFormVO) {
        if (StrUtil.isBlank(companyForgotFormVO.getCode())) {
            return JsonResult.error("验证码为空");
        }

        if (StrUtil.isBlank(companyForgotFormVO.getCodeKey())) {
            return JsonResult.error("验证码为空!");
        }

        String today = DatePattern.PURE_DATE_FORMAT.format(new DateTime());
        if (Boolean.FALSE.equals(redisTemplate.hasKey(today + companyForgotFormVO.getCodeKey()))) {
            return JsonResult.error("验证码已过期");
        }

        String redisCode = redisTemplate.opsForValue().get(today + companyForgotFormVO.getCodeKey());
        if (!companyForgotFormVO.getCode().equalsIgnoreCase(redisCode)) {
            return JsonResult.error("验证码不正确");
        }

        return companyService.forgotCompany(companyForgotFormVO);
    }



    @ApiOperation("单位信用代码模糊查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "organizationCode", value = "organizationCode", required = true, dataType = "String"),
    })
    @GetMapping("/publicly/company/get-by-part-code")
    public JsonResult getCompanyByPartOrganizationCode(String organizationCode) {
        if (StrUtil.isBlank(organizationCode)) {
            return JsonResult.error("单位社会统一信用代码为空");
        }
        return companyService.getCompanyByPartOrganizationCode(organizationCode);
    }

}
